
import Vue from 'vue'
import Vuex from 'vuex'

import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex)

function moduleIn (files, mode, reg) {
  if (!files) return
  mode = mode || 'object'
  const dJsReg = {
    underlineHead: /(\_|^\.\/|\.js$)/g,
    letterHead: /(^\.\/|\.js$)/g
  }
  reg = dJsReg[reg] || reg || dJsReg.underlineHead

  var modules = mode === 'array' ? [] : {}
  var objModules = {}

  files.keys().forEach(key => {
    var mk = key.replace(reg, '')
    var m = files(key)

    objModules[mk] = Object.keys(m).reduce((s, e) => {
      if (e !== 'default') s[e] = m[e]
      if (mode === 'array') modules = modules.concat(s)
      return s
    }, m.default || {})

    if (mode === 'single') modules = Object.assign({}, modules, objModules[mk])
  })

  if (mode === 'object') {
    modules = objModules
  } else {
    objModules = null
  }

  return modules
}

const files = require.context('./modules/', true, /_\S*\.js/)
const modules = moduleIn(files, 'object')


const store = new Vuex.Store({
	modules:modules,
	// #ifndef APP-PLUS
	plugins: [
		createPersistedState({
		  storage: window.localStorage,
		  key: "store",
		  reducer(state) { 
			return { ...state };
		  }
		})
		],
	// #endif
	
	// #ifdef APP-PLUS
	plugins: [createPersistedState({
	        // 传入参数
			storage: {
				getItem: (key) => uni.getStorageSync(key),
				setItem: (key, val) => uni.setStorageSync(key, val),
				removeItem: (key) => uni.removeStorageSync(key)
			},
			key: "store",
			
		})]
	// #endif
	
})

export default store
